import 'ol/ol.css';

import Map from 'ol/Map.js';
import View from 'ol/View.js';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';

import { AHT } from './AHT.js';
// import { AHT } from './AHT.ts';

export const initialize = (id) => {
    const CENTER = [0.0, 0.0];
    const map = new Map({ target: id, layers: [] });
    const view = new View({ projection: "EPSG:3857", zoom: 10, center: CENTER });
    const layer = new VectorLayer({ source: new VectorSource(), visible: true });
    map.setView(view);
    map.addLayer(layer);

    // 生成小车
    const ahts = [];
    const getRand = (num) => num - 2.0 * num * Math.random();
    for (let i = 0; i < 1000; i++) {
        const modeR = Math.round(Math.random() * 5.0);
        const coordinateR = [CENTER[0] + getRand(200000), CENTER[1] + getRand(200000)]; // 生成一个随机的位置
        const rotationR = Math.PI * Math.random();
        const aht = new AHT(view, layer);
        aht.setMode(modeR); // 设置负载模式
        aht.setCoordinate(coordinateR); // 设置 小车坐标 EPSG:4326
        aht.setRotation(rotationR); // 设置 小车旋转角度
        aht.setSacle(0.5); // 设置小车缩放比例
        aht.speed = 2.0 - 4.0 * Math.random(); // 这里生成一个随机的速度
        ahts.push(aht);
    }

    view.on("change:resolution", () => {
        for (let i = 0; i < ahts.length; i++) {
            const aht = ahts[i];
            aht.updateScale();
        }
    });

    const moveFeature = () => {

        for (let i = 0; i < ahts.length; i++) {
            const aht = ahts[i];
            const x = aht.coordinate[0];
            const y = aht.coordinate[1];
            const speed = aht.speed * 500;
            const rotation = aht.rotation;
            const deltaX = -speed * Math.sin(rotation);
            const deltaY = -speed * Math.cos(rotation);
            const pixelCoord = map.getPixelFromCoordinate([x + deltaX, y + deltaY]);
            const integerPixelCoord = [Math.round(pixelCoord[0]), Math.round(pixelCoord[1])];
            const geographicCoord = map.getCoordinateFromPixel(integerPixelCoord);
            aht.setCoordinate(geographicCoord);
        }

    }
    setInterval(() => { moveFeature(); }, 100);
};